"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.getRemoteConfigs = void 0;
var _request = require("./request");
var _fs = _interopRequireDefault(require("fs"));
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const getlatestSha = async ()=>{
    const result = await (0, _request).normalCraw('https://api.github.com/repos/flasco/origin-dist/branches/master');
    return result.commit.sha;
};
const getConfigContent = async ()=>{
    var ref, ref1;
    const sha = await getlatestSha();
    const result = await (0, _request).normalCraw(`https://api.github.com/repos/flasco/origin-dist/git/trees/${sha}`);
    const configTreeUrl = (ref = result.tree.filter((i)=>i.path === 'configs'
    ).pop()) == null ? void 0 : ref.url;
    if (!configTreeUrl) {
        throw new Error('初始化书源配置失败 - no config dir');
    }
    const configTree = await (0, _request).normalCraw(configTreeUrl);
    return configTree == null ? void 0 : (ref1 = configTree.tree) == null ? void 0 : ref1.filter((i)=>i.path.endsWith('.json')
    ).map((i)=>i.url
    );
};
const getRemoteConfigs = async ()=>{
    if (process.env.APP_ENV === 'development') {
        return [
            JSON.parse(_fs.default.readFileSync(_path.default.resolve(__dirname, '../../config/19zw.json'), 'utf-8')), 
        ];
    }
    const filesUrls = await getConfigContent();
    if (!(filesUrls == null ? void 0 : filesUrls.length)) {
        throw new Error('初始化书源配置失败 - read config tree content failed');
    }
    const files = await Promise.all(filesUrls.map((url)=>(0, _request).normalCraw(url).then((res)=>Buffer.from(res.content, 'base64').toString()
        )
    ));
    return files.map((file)=>JSON.parse(file)
    );
};
exports.getRemoteConfigs = getRemoteConfigs;
